package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.JedisUtil;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 类 名: LoginController
 * 描 述:
 * 作 者: 蔡畅
 * 创 建：2019年11月26日
 */
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private JedisUtil jedisUtil;

    @Reference
    MemberService memberService;

    /**
     * 描 述： 验证登录
     * 作 者： 蔡畅
     * 历 史： (版本) 作者 时间 注释
     *
     * @param
     * @return
     */


    @RequestMapping("/check")
    public Result check(@RequestBody Map map, HttpServletRequest request) {
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //1.比对验证码
        String redisCode = jedisUtil.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (redisCode == null || !redisCode.equals(validateCode)) {
            return Result.error("验证码错误,请重新输入!");
        }


        //2.看看是不是我们的会员,如果不是则自动注册
        Member member = memberService.findByTelephone(telephone);
        if (member == null) {
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            member = memberService.add(member);
        }
        //4 把用户信息保存在session
//        request.getSession().setAttribute("member",member);
        //把用户信息存入redis

        String token = UUID.randomUUID().toString();
        jedisUtil.setex(token, 60 * 60 * 24 * 15, JSON.toJSONString(member));
        return Result.success("登录成功", token);
    }
}
